package com.pls.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.pls.domain.Employee;
import com.pls.domain.EmployeeProjectMap;
import com.pls.domain.Project;
import com.pls.domain.Seat;
import com.pls.utilities.ConnectionManager;

public class ProjectDAOImpl implements ProjectDAO {

	Logger logger = Logger.getLogger(ProjectDAOImpl.class);

	private CallableStatement proc = null;
	private ResultSet rs = null;
	private ConnectionManager conManager;
	private Connection connection = null;

	// Stored procedures
	// Move to constants
	private final static String USP_GetEmployee_Projects = "{ call GetEmployeeProjects() }";

	@Override
	public EmployeeProjectMap getEmployeeProjects() throws SQLException,
			Exception {

		EmployeeProjectMap empProj = new EmployeeProjectMap();
		Map<Integer, List<Project>> projMap = new HashMap<Integer, List<Project>>();
		List<Project> projHolder = new ArrayList<Project>();
		empProj.setEmployeeProjectMap(projMap);
		

		try {
			// Method enter log
			logger.debug("Method getEmployeeProjects entered.");

			conManager = ConnectionManager.getInstance();
			connection = conManager.getConnection();
			proc = connection.prepareCall(USP_GetEmployee_Projects);

			rs = proc.executeQuery();

			while (rs.next()) {

				Project project = new Project();
				int empId = Integer.parseInt(rs.getString("employeeId"));

				project.setProjectId(Integer.parseInt(rs.getString("projectId")));
				project.setProjectName(rs.getString("projectCode"));

				if (empProj.getEmployeeProjectMap().containsKey(empId)) {
					projHolder = new ArrayList<Project>();
					projHolder.addAll(empProj.getEmployeeProjectMap()
							.get(empId));
					projHolder.add(project);
					empProj.getEmployeeProjectMap().remove(empId);
					empProj.getEmployeeProjectMap().put(empId, projHolder);
				} else {
					projHolder = new ArrayList<Project>();
					projHolder.add(project);
					empProj.getEmployeeProjectMap().put(empId, projHolder);
				}

			}

			rs.close();
			// Method exit log

		} catch (SQLException e) {
			logger.error("- Exception:" + e.getClass() + "-" + e.getMessage());
			throw e;
		} catch (ClassNotFoundException e) {
			logger.error("- Exception:" + e.getClass() + "-" + e.getMessage());
			throw e;
		} catch (Exception e) {
			logger.error("- Exception:" + e.getClass() + "-" + e.getMessage());
			throw e;
		} finally {
			try {
				proc.close();
			} catch (SQLException e) {
				logger.error(this.getClass() + "- Exception:" + e.getClass()
						+ "-" + e.getMessage());
				throw e;
			}
			connection.close();
		}

		logger.debug("Method getEmployeeProjects successfully executed.");
		return empProj;
	}

}
